package com.study.Caro;

import com.study.GameService.NetConnection.ClientThread;
import com.study.GameService.NetConnection.GameService;
import com.study.GameService.NetConnection.ServerThread;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

@SuppressLint("HandlerLeak")
public class Menu extends Activity {
	EditText serverIP;
	int play_mode = GameService.SERVER_MODE;
	ServerThread serverThread = null;
	ClientThread clientThread = null;
	int port = 0;
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.menu);
        
        final Button btnServer = (Button) findViewById(R.id.btnServer);
        final Button btnClient = (Button)findViewById(R.id.btnClient);
        
        btnServer.setOnClickListener(serverClick);
        btnClient.setOnClickListener(clientClick);
	}
	
	private Handler mainHandler = new Handler(){
		public void handleMessage(Message msg){
			// Change to Caro activity
			if(msg.arg1 == 1){
				Intent game = new Intent(Menu.this, Caro.class);
				game.putExtra("MODE", play_mode);
				startActivity(game);
			}
		}
	};
	
	OnClickListener serverClick = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			play_mode = GameService.SERVER_MODE;
			GameService game = GameService.GetInstance(play_mode, null);
			game.SetReceiver(mainHandler);
			game.GameStart();
		}
	};
	OnClickListener clientClick = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			final Dialog connect = new Dialog(Menu.this);
			connect.setContentView(R.layout.client_option);
			connect.setCancelable(true);
			connect.setTitle("Connect Game");
			Button serCreate = (Button) connect.findViewById(R.id.btnConnectConfirm);
			final EditText etIP = (EditText) connect.findViewById(R.id.etConnectIP);
			serCreate.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					connect.dismiss();
					play_mode = GameService.CLIENT_MODE;
					String ip = etIP.getText().toString();
					GameService game = GameService.GetInstance(play_mode, ip);
					game.SetReceiver(mainHandler);
					game.GameStart();
				}
			});
			
			connect.show();
			/*
			play_mode = GameService.CLIENT_MODE;			
			GameService game = GameService.GetInstance(play_mode, serverIP.getText().toString());
			game.SetReceiver(mainHandler);
			game.GameStart();
			*/
		}
	};
}
